<?php

namespace App\Providers;

use App\Guards\H5Guard;
use App\Models\Kms\Auth\KmsClientModel;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Route;
use Laravel\Passport\Passport;
use Laravel\Passport\RouteRegistrar;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array<class-string, class-string>
     */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Auth::provider('h5', function($app, array $config) {
            // 返回 H5ServiceProvider 实例
            return new H5ServiceProvider($app['hash'], $config['model']);
        });

        Auth::extend('h5', function ($app, $name, array $config) {
            // 返回 H5Guard 实例
            return new H5Guard(Auth::createUserProvider($config['provider']), $app['request']);
        });

        if (!isset($_SERVER["COMPOSER_BINARY"])) {
            Passport::loadKeysFrom(resource_path("Secrets/OauthKey"));
            Passport::useClientModel(KmsClientModel::class);
            Passport::enableImplicitGrant();
            Passport::routes(function (RouteRegistrar $routeRegistrar) {
//            $this->forAuthorization();
                $routeRegistrar->forAccessTokens();
                $routeRegistrar->forTransientTokens();
                $routeRegistrar->forPersonalAccessTokens();
            });


            Passport::tokensExpireIn(now()->addDays(30));
            Passport::refreshTokensExpireIn(now()->addDays(45));
            Passport::personalAccessTokensExpireIn(now()->addMonths(6));
        }
    }


    /**
     * Register the routes needed for authorization.
     *
     * @return void
     */
    public function forAuthorization()
    {
        Route::group(['middleware' => ['web', 'kmsAuth:kmsApi']], function ($router) {
            $router->get('/authorize', [
                'uses' => 'AuthorizationController@authorize',
                'as'   => 'passport.authorizations.authorize',
            ]);

            $router->post('/authorize', [
                'uses' => 'ApproveAuthorizationController@approve',
                'as'   => 'passport.authorizations.approve',
            ]);

            $router->delete('/authorize', [
                'uses' => 'DenyAuthorizationController@deny',
                'as'   => 'passport.authorizations.deny',
            ]);
        });
    }
}
